# coding=utf-8
import os

import arcgisscripting
import arcpy
import retry


arcpy.env.overwriteOutput = 1
arcpy.CheckOutExtension("Spatial")



def extract(hdf_dir, NDVI_dir):
    if not os.path.exists(NDVI_dir):
        os.makedirs(NDVI_dir)
    arcpy.CheckOutExtension("Spatial")
    arcpy.env.workspace = hdf_dir
    hdfList = arcpy.ListRasters('*', 'HDF')
    for hdf in hdfList:
        Name = hdf[:-4] + ".tif"
        print Name
        # 提取波段0，对应波段与ArcGIS中显示的一致
        try:
            data = arcpy.ExtractSubDataset_management(hdf, NDVI_dir + Name, "0")
        except:
            continue
    print "OK！"


def get_hdf_dir(hdf_dir):
    hdf = os.listdir(hdf_dir)
    for i in hdf:
        if os.path.isfile(hdf_dir+i):
            hdf.remove(i)
    for i in range(len(hdf)):
        hdf[i] = hdf_dir+hdf[i]
    return hdf



if __name__ == '__main__':
    path = u"E:\\毕设数据\\原始数据\\"
    hdf_path = get_hdf_dir(path)

    NDVI_root_path = u"E:\\毕设数据\\NDVI\\"
    # for i in range(len(hdf_path)):
    #     print hdf_path[i]
    #
    #     try:
    #         extract(hdf_path[i], NDVI_root_path+hdf_path[i][-4:]+"\\")
    #         print hdf_path[i] + " OK!"
    #     except arcgisscripting.ExecuteError:
    #         print "err"
    #         continue
    for i in range(len(hdf_path)):
        # print hdf_path[i]
        if hdf_path[i][-4:] == "2007":
            print hdf_path[i]
            try:
                extract(hdf_path[i], NDVI_root_path + hdf_path[i][-4:] + "\\")
            except:
                continue
